"""


"""
from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.my_pagination import MyPageNumberPagination
from meiduo_admin.serializers.SPU_serializers import SPUSerializer, BrandSerializer, GoodsGategoriesSerializer
from utils.fdfs.MyFileStorage import MyStorage


class SPUListView(ModelViewSet):
    queryset = SPU.objects.all().order_by("id")
    serializer_class = SPUSerializer
    pagination_class = MyPageNumberPagination

    def brand(self, request):
        brand = Brand.objects.all()

        serializer = BrandSerializer(instance=brand, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)

    def categories(self, request):
        categories = GoodsCategory.objects.filter(parent_id=None)

        serializer = GoodsGategoriesSerializer(instance=categories, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)

    def sub_categories(self, request, pk):
        # 两种获取主键的方法
        parent_id = self.kwargs.get("pk")

        sub_categories = GoodsCategory.objects.filter(parent_id=parent_id)

        serializer = GoodsGategoriesSerializer(instance=sub_categories, many=True)

        return Response(serializer.data, status=status.HTTP_200_OK)

    def images_uploader(self, request):

        image = request.FILES.get("image")

        mystorage = MyStorage()

        img_url = mystorage.save(None, content=image)

        if not img_url:
            return Response({"errmsg": "上传失败"}, status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response({
                "img_url": settings.BASE_URL + img_url
            })
